package com.bolao;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutionException;

import org.apache.http.NameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.ViewPager;
import android.view.Menu;
import android.view.MenuItem;
import android.view.Window;
import android.widget.Toast;

import com.CustomClasses.JSONParser;
import com.facebook.FacebookException;
import com.facebook.FacebookOperationCanceledException;
import com.facebook.HttpMethod;
import com.facebook.Request;
import com.facebook.Response;
import com.facebook.Session;
import com.facebook.model.GraphMultiResult;
import com.facebook.model.GraphObject;
import com.facebook.model.GraphObjectList;
import com.facebook.model.GraphUser;
import com.facebook.widget.WebDialog;
import com.facebook.widget.WebDialog.OnCompleteListener;

import facebook.login.MainActivity;


public class MainTabActivity extends FragmentActivity {

	@Override
	protected void onResume() {
		super.onResume();
		mContext = getApplicationContext();
		
	};
	
	public static Context getmContext() {
		if(mContext==null){
			//OQQQQQQ FAZER
		}
		return mContext;
	}


	private static final int MENU_INVITE_FRIENDS = Menu.FIRST;
	private static final int MENU_LOGOUT = Menu.FIRST+1;
	private static final int MENU_VIEW_FRIENDS_BETS = MENU_LOGOUT+1;
	ViewPager mViewPager;
	private static GraphUser user;
	private static Context mContext;

	/**
	 * @return the user
	 */
	public static GraphUser getUser() {
		if(user==null){
			 getmContext().startActivity(new Intent( getmContext(), LoadingActivity.class));
		}
		return user;
	}

	/**
	 * @param user the user to set
	 */
	public static void setUser(GraphUser user) {
		MainTabActivity.user = user;
	}

	public boolean isOnline() {
	    ConnectivityManager cm =
	        (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
	    NetworkInfo netInfo = cm.getActiveNetworkInfo();
	    if (netInfo != null && netInfo.isConnectedOrConnecting()) {
	        return true;
	    }
	    return false;
	}


	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
		setContentView(R.layout.activity_tab_ativity);
		mViewPager = (ViewPager) findViewById(R.id.pager);
		mContext = getApplicationContext();
		if(isOnline()){
		SectionsPagerAdapter adapter = new SectionsPagerAdapter(getSupportFragmentManager(), getApplicationContext());
		mViewPager.setAdapter(adapter);

		} else {
			// 1. Instantiate an AlertDialog.Builder with its constructor
			AlertDialog.Builder builder = new AlertDialog.Builder(this);

			// 2. Chain together various setter methods to set the dialog characteristics
			builder.setMessage(R.string.no_connection_message)
			       .setTitle(R.string.no_connection_title);

			// 3. Get the AlertDialog from create()
			AlertDialog dialog = builder.create();
			dialog.show();
		}
	}
	
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		menu.add(Menu.NONE, MENU_INVITE_FRIENDS, Menu.NONE, "Invite Friends");
		menu.add(Menu.NONE, MENU_LOGOUT, Menu.NONE, "Logout");
		menu.add(Menu.NONE, MENU_VIEW_FRIENDS_BETS, Menu.NONE, "View Friends Bets");
		getMenuInflater().inflate(R.menu.tab_ativity, menu);	
		return true;
	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
	    switch (item.getItemId()) {
	        case MENU_LOGOUT:
	        	logout();
	            return true;
	        case MENU_INVITE_FRIENDS:
	        	inviteFriends();
	        case MENU_VIEW_FRIENDS_BETS:
	        	viewFriends();
	        default:
	            return super.onOptionsItemSelected(item);
	    }
	}
	
	private void viewFriends() {
		
		Session activeSession = Session.getActiveSession();

		new Request( activeSession,"/me/friends", null, HttpMethod.GET,  new Request.Callback() {
					@Override
					public void onCompleted(Response response) {
						 GraphMultiResult multiResult = response
						            .getGraphObjectAs(GraphMultiResult.class);
						    GraphObjectList<GraphObject> data = multiResult.getData();
						    List<GraphUser> friends = data.castToListOf(GraphUser.class);
						    
						    try {
								List<String> list = new GetAllUsers().execute().get();
							 						    
						    for(GraphUser gu: friends){
						    	if(list.contains(gu.getId())){
						    		
						    	}
						    }
						    
							}catch (InterruptedException e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							} catch (ExecutionException e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							}
					}
			    }
			).executeAsync();
		
		
	}

	private void inviteFriends(){
		Bundle params = new Bundle();
	    params.putString("message", "Try WCC!");
	    
	    WebDialog requestsDialog = (
	        new WebDialog.RequestsDialogBuilder(this,
	            Session.getActiveSession(),
	            params))
	            .setOnCompleteListener(new OnCompleteListener() {
	                @Override
	                public void onComplete(Bundle values,
	                    FacebookException error) {
	                    if (error != null) {
	                        if (error instanceof FacebookOperationCanceledException) {
	                            Toast.makeText(getApplicationContext(), 
	                                "Request cancelled", 
	                                Toast.LENGTH_SHORT).show();
	                        } else {
	                            Toast.makeText(getApplicationContext(), 
	                                "Network Error", 
	                                Toast.LENGTH_SHORT).show();
	                        }
	                    } else {
	                        final String requestId = values.getString("request");
	                        if (requestId != null) {
	                            Toast.makeText(getApplicationContext(), 
	                                "Request sent",  
	                                Toast.LENGTH_SHORT).show();
	                        } else {
	                            Toast.makeText(getApplicationContext(), 
	                                "Request cancelled", 
	                                Toast.LENGTH_SHORT).show();
	                        }
	                    }   
	                }
	            })
	            .build();
	    requestsDialog.show();
	}

	private void logout(){
    	Session.getActiveSession().close();
    	startActivity(new Intent(this, MainActivity.class));
	}

	class GetAllUsers extends AsyncTask<Void, String, List<String>>{

		private static final String GET_USER_LIST = "http://www.worldcupcompendium.com/android_connect/get_user_list.php";

		@Override
		protected List<String> doInBackground(Void... params) {
			JSONParser jParser = new JSONParser();
	    	List<NameValuePair> param = new ArrayList<NameValuePair>();
	    	JSONObject json = jParser.makeHttpRequest(GET_USER_LIST, "GET", param);
	    	List<String> list = new ArrayList<String>();
	    	try {
	    		JSONArray jsonArray = json.getJSONArray("user_list");
				for(int i = 0;i< jsonArray.length();i++){
					list.add((String) jsonArray.getJSONObject(i).get("user_id"));
				}
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			return list;
		}
		
	}


}
